<?php
/**
 * Created by PhpStorm.
 * User: krystal
 * Date: 2019/2/27
 * Time: 10:31
 */

namespace app\api\controller\v10;

use app\api\controller\v2\Auth;
use app\api\controller\v9\OrdersPay;
use app\common\cachemodel\Rectification;
use app\common\lib\Orders as OrdersLib;
use app\common\model\Orders as OrdersModel;
use app\common\model\Recode;
use app\common\model\ZhunleCounselorProblemRecode;
use app\common\model\ZhunleCourse;
use think\Db;
use think\Log;


/**
 * 教学视频订单相关接口
 * Class Orders
 * @package app\api\controller\v9
 */
class Orders extends Auth
{
    protected $nodel;
    private $acg_gids;
    private $fortune_gids;
    private $day_gids;
    private $video_gids;
    protected $msg;

    public function _initialize()
    {
        parent::_initialize();

        $this->acg_gids = config('goods.acg_id');
        $this->fortune_gids = config('goods.fortune_id');
        $this->day_gids = config('goods.day_id');
        $this->nodel = config('code.nodel');
        $this->video_gids = config('goods.video_id');
    }

    /**
     * 订单列表相关评价
     * @return \think\response\Json
     */
    public function index()
    {
        if (!request()->isGet())
        {
            return show(config('code.error'), '未知操作', [], 403);
        }
        $type = input('get.type/d', 0);

        $page = input('get.page/d', 1);

        $uid = $this->user['id'];

        //判断订单是否超时未支付
        check_overtime($uid);

        $OrdersModel = new OrdersModel();

        $orders = $OrdersModel->getUidOrders(['uid' => $uid, 'type' => $type, 'is_del' => $this->nodel, 'page' => $page], 2);

        //将数据根据创建时间排序
        array_multisort(array_column($orders, 'create_time'), SORT_NUMERIC, SORT_DESC, $orders);

        $RecodeModel = new Recode();

        //重组订单数据
        $start_time = '';
        $end_time = '';

        $data = [];

        if ($orders || !empty($orders))
        {
            foreach ($orders as $k => $v)
            {

                if (isset($v['type']) && $v['type'])
                {
                    switch ($v['type'])
                    {
                        case 1:
                            $start_time = date('Y-m-d', $v['time']);
                            $end_time = date('Y-m-d', strtotime($v['expire_time'], $v['time']) - 86400);
                            break;
                        case 2:
                            $start_time = date('Y-m', $v['time']);
                            $end_time = date('Y-m', strtotime($v['expire_time'], $v['time']) - 86400);
                            break;
                        case 3:
                            $start_time = date('Y', $v['time']);
                            $end_time = date('Y', strtotime($v['expire_time'], $v['time']) - 86400);
                            break;
                    }
                }

                $or_price = $v['or_prize'];
                $now_price = $v['now_prize'];
                $total_amount = $v['total_amount'];
                $create_time = date('Y-m-d H:i:s', $v['create_time']);

                //商品活动折扣
                $activeDiscount = active($v['gid']);
                if ($activeDiscount['discount'] && !$this->is_apple_pay)
                {
                    $now_price *= $activeDiscount['discount'];
                }

                //校准生辰订单数据
                if ($v['gid'] == 1)
                {
                    if ($this->is_apple_pay)
                    {
                        $or_price = $this->apple_goods['rec_goods']['or_prize'];
                        $now_price = $this->apple_goods['rec_goods']['now_prize'];
                    }

                    $data[] = [
                        'type' => 1,
                        'rectification_data' => [
                            'id' => $v['reid'],
                            'birth' => date('Y-m-d', $v['start_time']),
                            'start_time' => date('H:i', $v['start_time']),
                            'end_time' => date('H:i', $v['end_time']),
                            'or_prize' => sprintf('%.2f', $or_price),
                            'now_prize' => sprintf('%.2f', $now_price),
                        ],
                        'status' => $v['restatus'] ?? 0,//校准生辰缓存字段不存在时，默认未支付
                        'create_time' => $create_time,
                        'order_id' => $v['order_id'],
                        'trade_type' => $v['trade_type'],
                        'count' => 1,
                        'total_price' => sprintf('%.2f', $total_amount),
                    ];
                }//运势订单数据(运势)
                elseif (in_array($v['gid'], $this->fortune_gids))
                {
                    $a[] = $v;
                    $array = [];
                    $rids_array = explode(',', $v['rids']);
                    foreach ($rids_array as $kk => $vv)
                    {
                        if ($vv)
                        {
                            try
                            {

                                $rname = $RecodeModel->getRecode(['uid' => $this->user['id'], 'id' => $vv]);

                            }
                            catch (\Exception $e)
                            {

                                $rname = [
                                    'id' => $vv,
                                    'name' => '未找到',
                                ];
                                \think\Log::write('异常档案id：' . $vv, 'error', true);
                            }
                        } else
                        {
                            $rname = [
                                'id' => $vv,
                                'name' => '未找到',
                            ];
                        }

                        if ($this->is_apple_pay)
                        {
                            foreach ($this->apple_goods['fortune_goods'] as $fortune_day_good)
                            {
                                if ($fortune_day_good['id'] == $v['gid'])
                                {
                                    $or_price = $fortune_day_good['or_prize'];
                                    $now_price = $fortune_day_good['now_prize'];
                                }
                            }
                        } else
                        {
                            //商品活动折扣
                            $activeDiscount = active($v['gid']);
                            if ($activeDiscount['discount'] && !$this->is_apple_pay)
                            {
                                $now_price = $v['now_prize'] * $activeDiscount['discount'];
                            }
                        }


                        $array[] = [
                            'id' => $rname['id'],
                            'gid' => $v['gid'],
                            'rname' => $rname['name'],
                            'fortune_type' => $v['type'],
                            'start_time' => $start_time,
                            'end_time' => $end_time,
                            'or_price' => sprintf('%.2f', $or_price),
                            'now_price' => sprintf('%.2f', $now_price),
                        ];
                    }
                    //新版订单状态统一，已完成为4,只有日运
                    if (in_array($v['gid'], $this->day_gids) && $v['status'] == 4)
                    {
                        $fortune_status = 1;
                    } else
                    {
                        $fortune_status = $v['status'];
                    }
                    $data[] = [
                        'type' => 2,
                        'fortune_data' => $array,
                        'create_time' => $create_time,
                        'order_id' => $v['order_id'],
                        'status' => $fortune_status,
                        'trade_type' => $v['trade_type'],
                        'count' => count($array),
                        'total_price' => sprintf('%.2f', $total_amount),
                    ];

                }//命格线订单数据
                elseif (in_array($v['gid'], $this->acg_gids))
                {
                    $gname = [];

                    try
                    {

                        $rname = $RecodeModel->getRecode(['uid' => $this->user['id'], 'id' => $v['rid']]);

                    }
                    catch (\Exception $e)
                    {

                        $rname = [
                            'name' => '未找到',
                        ];
                        \think\Log::write('异常档案id：' . $v['rid'], 'error', true);
                    }

                    try
                    {
                        $ogoods = Db::table('app_orders_goods')
                            ->alias('og')
                            ->join('app_goods g', 'og.gid=g.id', 'LEFT')
                            ->field('g.name')
                            ->where(['og.oid' => $v['oid']])
                            ->selectOrFail();

                    }
                    catch (\Exception $e)
                    {

                        \think\Log::write('异常订单id：' . $v['oid'], 'error', true);

                        return show(config('code.error'), '订单异常');
                    }

                    foreach ($ogoods as $i => $g)
                    {
                        $gname[] = $g['name'];
                    }

                    $data[] = [
                        'type' => 3,
                        'acgmap_data' => [
                            'order_name' => '幸运之城',
                            'order_sub_name' => '幸运之城解锁',
                            'order_sub_rname' => $rname['name'],
                            'order_sub_names' => implode(',', $gname),
                        ],
                        'total_price' => $total_amount,
                        'create_time' => $create_time,
                        'order_id' => $v['order_id'],
                        'status' => $v['status'],
                        'trade_type' => $v['trade_type'],
                        'count' => count($ogoods),
                    ];

                } elseif (in_array($v['gid'], $this->video_gids))
                {
                    //获取相关课程信息
                    $ZhunleCourseModel = new ZhunleCourse();

                    $course = $ZhunleCourseModel->getCourseInfo(['gid' => $v['gid']]);

                    if ($course === false)
                    {
                        return show(config('code.error'), $ZhunleCourseModel->getError());
                    }


                    if ($this->is_apple_pay)
                    {
                        foreach ($this->apple_goods['video_goods'] as $fortune_day_good)
                        {
                            if ($fortune_day_good['id'] == $v['gid'])
                            {
                                $or_price = $fortune_day_good['or_prize'];
                                $now_price = $fortune_day_good['now_prize'];
                            }
                        }
                    } else
                    {
                        $or_price = $course['or_prize'];
                        //商品活动折扣
                        $activeDiscount = active($v['gid']);
                        if ($activeDiscount['discount'] && !$this->is_apple_pay)
                        {
                            $now_price = $course['now_prize'] * $activeDiscount['discount'];
                        } else
                        {
                            $now_price = $course['now_prize'];
                        }
                    }
                    //新版订单状态统一，已完成为4
                    if ($v['status'] == 4)
                    {
                        $video_status = 1;
                    } else
                    {
                        $video_status = $v['status'];
                    }
                    $data[] = [
                        'type' => 4,
                        'video_data' => [
                            'id' => $course['id'],
                            'order_name' => '课程',
                            'order_sub_name' => '占星课程',
                            'course_title' => $course['title'],
                            'or_price' => sprintf('%.2f', $or_price),
                            'now_price' => sprintf('%.2f', $now_price),
                        ],
                        'total_price' => sprintf('%.2f', $total_amount),
                        'create_time' => $create_time,
                        'order_id' => $v['order_id'],
                        'status' => $video_status,
                        'trade_type' => $v['trade_type'],
                        'count' => 1,
                    ];
                }
            }
        }


        // 统计有多少订单
        $total = count($data);
        //获取数据分页信息
        $per_page = 20;// 当前订单订单每页显示数量
        $data_list = getPaginatorData($total, $page, $per_page);
        //获取分页后的数据
        $data_list['data'] = array_slice($data, $data_list['start'], $per_page);
        unset($data_list['start']);
        unset($data_list['end']);

        return show(config('code.success'), '加载成功', $data_list);
    }

    /**
     * 订单详情相关接口
     * @param['type']  [1=>校准生辰,2=>运势,3=>命运之城,4=>教学视频，5=>占星，6=>提问,7=>围观]
     * @return \think\response\Json
     * @throws \app\common\lib\exception\ApiException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function read()
    {
        if (!request()->isGet())
        {
            return show(config('code.error'), '未知操作', [], 403);
        }

        $param = $this->request->only(['order_id']);

        $uid = $this->user['id'];

        $validate = validate('Orders');

        //验证请求参数
        if ($validate->scene('read')->check($param) !== true)
        {
            return show(config('code.error'), (string)$validate->getError());
        }

        //支付客户端判断该订单是否已经支付,若已经支付,但是status=0;就更改status=1
        (new OrdersLib())->validateOrders($param['order_id']);
        $OrdersModel = new OrdersModel();
        $ZhunleRecodeModel = new ZhunleCounselorProblemRecode();
        $order_ids[] = $param['order_id'];
        $order_type = (int)substr($param['order_id'], 1, 1);

        if ($order_type == 3)
        {
            $field = 'or.uid,og.gid,g.name,g.or_prize,g.now_prize,g.expire_time,or.id oid,or.status,or.order_id,or.uid,or.trade_type,or.total_amount,or.create_time,or.pay_time,or.return_time,og.rid,or.account,or.order_type';
            $orders = $OrdersModel->alias('or')
                ->field($field)
                ->join('wechat_backup_07_18_14_43_00.app_orders_goods og', 'or.id=og.oid', 'INNER')
                ->join('wechat_backup_07_18_14_43_00.app_goods g', 'og.gid=g.id', 'INNER')
                ->where('or.order_id', $param['order_id'])
                ->order('or.create_time', 'DESC')
                ->selectOrFail();
        } else
        {
            //获取订单数据
            $orders = $OrdersModel->getOrdersDetail(['order_type' => $order_type, 'order_id' => $order_ids, 'uid' => $uid]);
        }


        if (is_array($orders) && $orders)
        {
            $num = 1;
            $arr = [];
            $or_total = 0;
            //重组订单数据
            foreach ($orders as $data)
            {
                if ($data['uid'] != $this->user['id'])
                {
                    Log::write('非法订单查询：' . json_encode($param, true), 'error', true);
                    return show(config('code.error'), '服务异常，请稍后重试～');
                }
                //新版订单状态统一，已完成为4,只有日运和教学视频
                if (in_array($data['order_type'], [2, 6]) && $data['status'] == 4)
                {
                    $arr['status'] = 1;
                } else
                {
                    $arr['status'] = $data['status'];
                }
                $create_time = date('Y-m-d H:i:s', $data['create_time']);
                $return_time = $data['return_time'] ? date('Y-m-d H:i:s', $data['return_time']) : 0;
                //获取订单商品原价与现价
                if (isset($data['or_prize']) && isset($data['now_prize']))
                {
                    //  判断是否是applePay
                    if ($this->is_apple_pay)
                    {
                        switch ($order_type)
                        {
                            case 1:
                                $data['or_price'] = $this->apple_goods['rec_goods']['or_prize'];
                                $data['now_price'] = $this->apple_goods['rec_goods']['now_prize'];
                                break;
                            case 2:
                                foreach ($this->apple_goods['fortune_goods'] as $ap)
                                {
                                    if ($data['gid'] == $ap['id'])
                                    {
                                        $data['or_price'] = $ap['or_prize'];
                                        $data['now_price'] = $ap['now_prize'];
                                    }
                                }
                                break;
                            case 3:
                                foreach ($this->apple_goods['acg_goods'] as $ap)
                                {
                                    if ($data['gid'] == $ap['id'])
                                    {
                                        $data['or_price'] = $ap['or_prize'];
                                        $data['now_price'] = $ap['now_prize'];
                                    }
                                }
                                break;
                            case 4;
                                foreach ($this->apple_goods['video_goods'] as $ap)
                                {
                                    if ($data['gid'] == $ap['id'])
                                    {
                                        $data['or_price'] = $ap['or_prize'];
                                        $data['now_price'] = $ap['now_prize'];
                                    }
                                }
                                break;
                        }
                    } else
                    {
                        $data['or_price'] = sprintf("%.2f", $data['or_prize']);
                        $data['now_price'] = sprintf("%.2f", $data['now_prize']);
                        //商品活动折扣
                        $activeDiscount = active($data['gid']);
                        if ($activeDiscount['discount'] && !$this->is_apple_pay)
                        {
                            $data['now_price'] *= $activeDiscount['discount'];
                        }
                    }

                } else
                {
                    $data['or_price'] = sprintf("%.2f", $data['counselor_price']);
                    $data['now_price'] = sprintf("%.2f", $data['counselor_price']);
                }

                //获取不同类型订单的详情数据
                switch (true)
                {
                    //运势
                    case $order_type == 2:
                        $arr['fortune'] = $this->FortuneRead($data);
                        $num = count($arr['fortune']);
                        $or_total = $data['or_price'] * $num;
                        break;
                    //幸运之城
                    case $order_type == 3:
                        $arr['lines'][] = $this->MapRead($data);
                        $num = count($arr['lines']);
                        $or_total += $data['or_price'];
                        break;
                    //教学视频
                    case $order_type == 4:
                        $arr['video'] = $this->VideoRead($data);
                        $or_total = $data['or_price'];
                        break;
                    //平台
                    case $order_type == 5:
                        $divination = [
                            'planet' => config('astro.planet_name')[$data['planet']],
                            'sign' => config('astro.sign_name')[$data['sign']],
                            'house' => $data['house'] . '宫'
                        ];
                        $data['divination'] = implode(' ', $divination);
                        $data['name'] = '提问咨询';
                        $arr['questions_data'] = $this->PlatformRead($data);
                        $or_total = $data['or_price'];
                        break;
                    case $order_type == 6:
                        $recode = array_values($ZhunleRecodeModel->getProblemRecodeName($data['bind_id']));
                        foreach ($recode as $r)
                        {
                            $data['recode'][] = $r['name'];
                        }
                        $data['name'] = '占星咨询';
                        $arr['questions_data'] = $this->PlatformRead($data);
                        $or_total = $data['or_price'];
                        break;
                    case $order_type == 7:
                        $data['name'] = '围观';
                        $arr['questions_data'] = $this->PlatformRead($data);
                        $or_total = $data['or_price'];
                        break;
                }

                //获取订单购买份数
                $arr['count'] = $num;
                //获取订单不同状态时的相关时间
                switch (true)
                {
                    //校准生辰,月运,年运,幸运之城有计算中
                    case in_array($data['order_type'], [1, 3, 4, 5]) && $data['status'] == 1:
                        $arr['desc'] = '您购买的相关内容正在计算中';
                        $arr['order'] = [
                            0 => [
                                'name' => '创建时间',
                                'value' => $create_time
                            ],
                            1 => [
                                'name' => '支付时间',
                                'value' => date('Y-m-d H:i:s', $data['pay_time'])
                            ],
                        ];
                        break;
                    case (in_array($data['order_type'], [1, 3, 4, 5]) && in_array($data['status'], [2, 3, 4])) || (in_array($data['order_type'], [2, 6]) && in_array($data['status'], [1, 4])):
                        $arr['desc'] = '您购买的相关内容已成功解锁';
                        $arr['order'] = [
                            0 => [
                                'name' => '创建时间',
                                'value' => $create_time
                            ],
                            1 => [
                                'name' => '支付时间',
                                'value' => date('Y-m-d H:i:s', $data['pay_time'])
                            ],
                        ];
                        break;
                    case $data['status'] == 2:
                        $arr['desc'] = '24小时之内未付款订单自动关闭~';
                        $arr['desc1'] = '您购买的相关内容已成功解锁~';
                        $arr['order'] = [
                            0 => [
                                'name' => '创建时间',
                                'value' => $create_time
                            ]
                        ];
                        break;
                    default:
                        $arr['desc'] = '您的订单还没有支付~';
                        $arr['order'] = [
                            0 => [
                                'name' => '创建时间',
                                'value' => $create_time
                            ]
                        ];
                        break;
                }

                $arr['or_total_price'] = sprintf("%.2f", $or_total);
                $arr['total_price'] = sprintf("%.2f", $data['total_amount']);
                $arr['trade_type'] = $data['trade_type'];
                $arr['order_id'] = $param['order_id'];
                $arr['order_type'] = $order_type;
            }


            if ($return_time)
            {
                $arr['desc'] = '您申请的退款已成功退回到您的账户~';
                $arr['order'][] = [
                    'name' => '退款时间',
                    'value' => $return_time
                ];
            }

            return show(config('code.success'), '加载成功', $arr);
        } else
        {
            return show(config('code.error'), '当前订单不存在');

        }
    }

    /**
     * 运势订单详情
     * @param array $data
     * @return array|\think\response\Json
     * @throws \app\common\lib\exception\ApiException
     */
    private function FortuneRead($data = [])
    {
        switch ($data['type'])
        {
            case 1:
                $start_time = date('Y-m-d', $data['time']);
                $end_time = date('Y-m-d', strtotime($data['expire_time'], $data['time']) - 86400);
                break;
            case 2:
                $start_time = date('Y-m', $data['time']);
                $end_time = date('Y-m', strtotime($data['expire_time'], $data['time']) - 86400);
                break;
            case 3:
                $start_time = date('Y', $data['time']);
                $end_time = date('Y', strtotime($data['expire_time'], $data['time']) - 86400);
                break;
            default :
                return show(config('code.error'), '订单详情获取失败');
        }

        $RecodeModel = new Recode();
        $rids = explode(',', $data['rids']);
        $arr = [];
        if ($rids)
        {
            foreach ($rids as $k => $v)
            {
                $rname = $RecodeModel->getRecode(['uid' => $this->user['id'], 'id' => $v]);
                $arr[] = [
                    'id' => $rname['id'],
                    'gid' => $data['gid'],
                    'rname' => $rname['name'],
                    'fortune_type' => $data['type'],
                    'start_time' => $start_time,
                    'end_time' => $end_time,
                    'or_price' => sprintf('%.2f', $data['or_price']),
                    'now_price' => sprintf('%.2f', $data['now_price']),
                ];
            }
        }

        return $arr;
    }

    /**
     * 幸运之城订单详情
     * @param array $data
     * @return array
     * @throws \app\common\lib\exception\ApiException
     */
    private function MapRead($data = [])
    {
        //重组订单详情数据
        $RecodeModel = new Recode();
        //获取当前订单的档案信息
        $recode = $RecodeModel->getRecode(['uid' => $this->user['id'], 'id' => $data['rid']]);

        if ($recode['isself'] == 1)
        {
            $rname = '自己';
        } else
        {
            $rname = $recode['name'];
        }

        $now_price = $data['now_price'];

        $array = [
            'rid' => $data['rid'],
            'rname' => $rname,
            'name' => $data['name'],
            'or_price' => sprintf('%.2f', $data['or_price']),
            'now_price' => sprintf("%.2f", $now_price),
        ];

        return $array;
    }

    /**
     * 教学视频订单详情
     * @param array $data
     * @return array
     */
    private function VideoRead($data = [])
    {
        $arr = [
            'id' => $data['cid'],
            'or_price' => sprintf('%.2f', $data['or_price']),
            'now_price' => sprintf('%.2f', $data['now_price']),
            'course_name' => '占星课程',
            'course_title' => $data['title'],
        ];
        return $arr;

    }

    /**
     * 平台订单详情
     * @param array $data
     * @return array
     */
    private function PlatformRead($data = [])
    {
        $arr = [
            'order_name' => $data['name'],
            'title' => $data['title'],
            'answer' => $data['answer'] ?? '',
            'recode' => $data['recode'] ?? [],
            'divination' => $data['divination'] ?? '',
            'or_price' => sprintf('%.2f', $data['or_price']),
            'now_price' => sprintf('%.2f', $data['now_price']),
            'cp_id' => $data['gid'],
        ];

        return $arr;
    }

    /**
     * 教学视频下单接口
     * @return \think\response\Json
     */
    public function pay_unlock()
    {
        if (!request()->isPost())
        {
            return show(config('code.error'), '未知操作', [], 403);
        }

        $param['id'] = input('param.id/d', 0);
        $param['trade_type'] = input('param.trade_type/d', 0);
        $this->CheckUnlock($param);

        $validate = validate('Orders');

        if ($validate->scene('v9_pay_unlock')->check($param) !== true)
        {
            return show(config('code.error'), json_encode($validate->getError(), true));
        }

        $trade_type = $param['trade_type'];// 支付方式
        $id = $param['id'];// 课程id
        $openid = input('param.openid', '');
        $callback_url = input('param.callback_url', '');

        $OrderPayModel = new OrdersPay();
        try
        {
            $data = $OrderPayModel->pay_unlock(['order_type' => 6, 'trade_type' => $trade_type, 'id' => $id, 'openid' => $openid, 'callback_url' => $callback_url]);
        }
        catch (\Exception $e)
        {
            return show(config('code.error'), '下单失败');
        }

        if ($data['status'] === true)
        {
            return show(config('code.success'), '下单成功', $data['data']);
        } else
        {
            return show(config('code.error'), '下单失败', $data['data']);
        }
    }

    /**
     * 检测下单参数
     * @param $param
     * @return string
     */
    private function CheckUnlock($param)
    {
        $this->msg = '';
        //1=>支付宝,2=>微信,5=>京东,6 微信公众号JSAPI,8 H5支付
        if (!in_array($param['trade_type'], [1, 2, 5, 6, 8], true))
        {
            return $this->msg = '未知的支付方式';
        }
        if (!$param['id'])
        {
            return $this->msg = '请选择课程';
        }
        if (!in_array($param['id'], config('goods.video_id')))
        {
            return $this->msg = '未知的课程';
        }
        return $this->msg;
    }

    /**
     * 校准生辰下单接口
     * @return \think\response\Json
     * @throws \app\common\lib\exception\ApiException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \Exception
     */
    public function pay_order()
    {
        if (!request()->isPost())
        {
            return show(config('code.error'), '未知操作', [], 403);
        }

        $param['trade_type'] = $trade_type = input('param.trade_type/d');// 支付方式
        $param['gid'] = $gid = input('param.gid/d');// 商品类型id   1=>校准生辰
        $param['reid'] = $id = input('param.id/d') ?? 0;// 商品id =>校准生辰id
        $openid = input('param.openid', '');
        $callback_url = input('param.callback_url', '');
        $this->CheckPayOrder($param);
        if ($this->msg)
        {
            Log::write('v10校准生辰下单请求参数有误：' . $this->msg, 'notice', true);
            return show(config('code.error'), $this->msg);
        }
        //下单统一
        $OrderPayModel = new OrdersPay();

        $data = $OrderPayModel->pay_unlock(['order_type' => 1, 'trade_type' => $trade_type, 'gid' => $gid, 'reid' => $id, 'openid' => $openid, 'callback_url' => $callback_url]);

        if ($data['status'] === true)
        {
            return show(config('code.success'), '下单成功', $data['data']);

        }

        return show(config('code.error'), '下单失败');
    }

    /**
     * 检测生时矫正下单参数
     * @param $param
     * @return string
     * @throws \Exception
     */
    private function CheckPayOrder($param)
    {
        $this->msg = '';
        //1=>支付宝,2=>微信,5=>京东,6 微信公众号JSAPI,8 H5支付
        if (!in_array($param['trade_type'], [1, 2, 5, 6, 8], true))
        {
            return $this->msg = '未知的支付方式';
        }
        if (!$param['gid'])
        {
            return $this->msg = '请选择商品';
        }
        if ($param['gid'] != 1)
        {
            return $this->msg = '商品信息错误';
        }

        if (!$param['reid'])
        {
            return $this->msg = '请填写事件';
        }
        $rec = (new Rectification())->getInfoById($param['reid']);
        if (!$rec)
        {
            return $this->msg = '无此生时矫正事件';
        }
        if ($rec['uid'] != $this->user['id'])
        {
            return $this->msg = '服务异常';
        }
        //状态 -1 已删除 ||  0未支付  ||  1等待矫正  || 2矫正成功  ||3矫正失败  ||  4 支付失败 || 5支付关闭 || 6退款成功
        if ($rec['status'])
        {
            return $this->msg = '当前校正已有订单，请重新确认';
        }
        return $this->msg;
    }
}
